package org.secure.sms;

import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.ContactsContract;
import android.telephony.SmsManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;
import android.widget.AdapterView.OnItemClickListener;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

public class SecureMessagesActivity extends Activity implements OnClickListener, OnItemClickListener, TextWatcher
{
    EditText edtMessage;
    EditText edtNumber;
    Button btnSend;
    Toast toast;
    boolean replying = false;
    static private Handler handler = new Handler();
    Runnable delayed;
    long delay = 10000;
    long minimum_wait = 600000;
//easter egggg
    private void sendDelayedMessage(final String number, final String message) {
        delayed = new Runnable() {
            @Override
            public void run() {
                toast.setText("Delayed message sent!");
                toast.show();
                sendSMS(number, message);
            }
        };

        handler.postDelayed(delayed, delay);
    }


    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        
        setTheme( android.R.style.Theme_Light );
        setContentView(R.layout.main);

        this.findViewById( R.id.UpdateList ).setOnClickListener( this );
        btnSend = (Button) findViewById(R.id.btnSendText);
        edtMessage = (EditText) findViewById(R.id.edtMessage);
        edtNumber = (EditText) findViewById(R.id.edtNumber);

        edtMessage.addTextChangedListener(this);
        btnSend.setOnClickListener(this);
        //edtNumber.addTextChangedListener();

        toast= Toast.makeText(getApplicationContext(),
                "Default toast", Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.TOP|Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    ArrayList<String> smsList = new ArrayList<String>();
    
	public void onItemClick( AdapterView<?> parent, View view, int pos, long id ) 
	{
        String[] splitted = smsList.get( pos ).split("\n");
        String sender = splitted[0];
        String datetime = splitted[1];

        SimpleDateFormat f = new SimpleDateFormat("MMM d, hh:mm a");
        Date d = null;
        try {
            d = f.parse(datetime);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        d.setYear(113);
        long sent_time = d.getTime();


        long current_time = System.currentTimeMillis();

        long howlonghasitbeen = current_time - sent_time;

        if(minimum_wait > howlonghasitbeen) {
            toast.setText("It hasn't been long enough");
            toast.show();
            return;
        }

        edtNumber.setText(getContactNumberFromName(sender));

        replying = true;
        btnSend.setText("Reply");
	}

	public void onClick( View v ) 
	{
        switch (v.getId()) {
            case R.id.UpdateList:
                ContentResolver contentResolver = getContentResolver();
                Cursor cursor = contentResolver.query( Uri.parse( "content://sms/inbox" ), null, null, null, null);


                int indexBody = cursor.getColumnIndex( SmsReceiver.BODY );
                int indexAddr = cursor.getColumnIndex( SmsReceiver.ADDRESS );
                int timeStamp = cursor.getColumnIndex( SmsReceiver.DATE);


                if ( indexBody < 0 || !cursor.moveToFirst() ) return;

                smsList.clear();

                do
                {
                    String str = getContactNameFromNumber(cursor.getString(indexAddr)) + "\n" + formatDate(cursor.getLong(timeStamp)) + "\n" + cursor.getString(indexBody);
                    smsList.add( str );
                }
                while( cursor.moveToNext() );


                ListView smsListView = (ListView) findViewById( R.id.SMSList );
                smsListView.setAdapter( new ArrayAdapter<String>( this, android.R.layout.simple_list_item_1, smsList) );
                smsListView.setOnItemClickListener(this);
                replying = false;
                btnSend.setText("Send");
                edtNumber.setText("");
                edtMessage.setText("");
                break;
            case R.id.btnSendText:

                if(replying == true) {
                    replying = false;
                    btnSend.setText("Send");
                    sendDelayedMessage(edtNumber.getText().toString(), edtMessage.getText().toString());
                } else {
                    if(edtNumber.getText().toString().length() == 10) {
                        if(edtMessage.getText().toString() != "") {
                            sendSMS(edtNumber.getText().toString(), edtMessage.getText().toString());
                        }
                    }
                }
                edtMessage.setText("");
                edtNumber.setText("");
        }
	}

    private void sendSMS(String phoneNumber, String message)
    {
        SmsManager sms = SmsManager.getDefault();
        sms.sendTextMessage(phoneNumber, null, message, null, null);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        if(s.length() > 10) {
            toast.setText("Too long");
            toast.show();
        }
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {

    }

    private class numberWatcher implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    }

    private String formatDate(long timestamp) {
        Date date = new Date(timestamp);
        String formattedDate = new SimpleDateFormat("MMM d, hh:mm a").format(date);

        return formattedDate;
    }

    private String getContactNameFromNumber(String number) {
        Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
        Cursor cursor = getApplicationContext().getContentResolver().query(uri, new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME},null,null,null);
        if (cursor.moveToFirst())
        {
            return cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
        }

        return "NOT FOUND";
    }

    private String getContactNumberFromName(String name) {
        String ret = null;
        String selection = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME+" like'%" + name +"%'";
        String[] projection = new String[] { ContactsContract.CommonDataKinds.Phone.NUMBER};
        Cursor c = getApplicationContext().getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                projection, selection, null, null);
        if (c.moveToFirst()) {
            ret = c.getString(0);
        }
        c.close();
        if(ret==null)
            ret = "Unsaved";
        return ret;
    }
}